package hn.cch.controller;


import hn.cch.entity.Order;
import hn.cch.entity.Product;
import hn.cch.entity.User;
import hn.cch.message.Request;
import hn.cch.message.Response;
import hn.cch.service.OrderService;
import hn.cch.service.ProductService;
import hn.cch.service.UserService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RequestMapping(value = "order")
@RestController
public class OrderController {

    private static Logger logger = LoggerFactory.getLogger(OrderController.class);


    @Autowired
    private OrderService orderService;




    @PostMapping(value = "addOne")
    public Response<Order> addOne(@RequestBody Request<Order> request) {
        logger.info("addOne");

        // 压力测试模拟并发，服务雪崩，服务容错
        /*
        模拟方案：
        在application.properties设置server.tomcat.max-threads=10
        使用JMeter设置20个线程循环100次访问addOne接口
        此时使用另外的工具访问getOne接口时会出现延时效果
         */

        // try {
        //     //模拟业务延时效果
        //     Thread.sleep(1000);
        // } catch (InterruptedException e) {
        //     // e.printStackTrace();
        //     logger.error(e.getMessage());
        // }


        return orderService.addOne(request);
    }


    @GetMapping(value = "getOne/{id}")
    public Order getOne(@PathVariable Integer id) {
        logger.info("getOne");
        return orderService.findById(id);
    }

    @PostMapping(value = "setOne")
    public Response<Order> setOne(@RequestBody Request<Order> request) {
        logger.info("setOne");
        //可以使用JSON字符串转转object对象模式获取数据
        // Order order = JsonUtil.toJsonObject(request.getData(), Order.class);
        //使用泛型更好
        Order order = request.getData();
        if (order != null) {
            order = orderService.save(order);
            Response response = Response.success();
            response.setInfo(order);
            return response;

        } else {
            return Response.failure();
        }


    }
}
